package org.dromara.vehicle.modules.vehicle.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.vehicle.modules.vehicle.domain.VehicleAnnualInspectionRecord;
import org.dromara.vehicle.modules.vehicle.domain.VehicleBasicInfo;
import org.dromara.vehicle.modules.vehicle.domain.VehicleInsuranceInfo;
import org.dromara.vehicle.modules.vehicle.domain.VehicleRepairRecord;
import org.dromara.vehicle.modules.vehicle.domain.bo.VehicleBasicInfoBo;
import org.dromara.vehicle.modules.vehicle.domain.vo.VehicleAnnualInspectionRecordVo;
import org.dromara.vehicle.modules.vehicle.domain.vo.VehicleBasicInfoVo;
import org.dromara.vehicle.modules.vehicle.domain.vo.VehicleInsuranceInfoVo;
import org.dromara.vehicle.modules.vehicle.domain.vo.VehicleRepairRecordVo;
import org.dromara.vehicle.modules.vehicle.mapper.VehicleBasicInfoMapper;
import org.dromara.vehicle.modules.vehicle.service.IVehicleAnnualInspectionRecordService;
import org.dromara.vehicle.modules.vehicle.service.IVehicleBasicInfoService;
import org.dromara.vehicle.modules.vehicle.service.IVehicleInsuranceInfoService;
import org.dromara.vehicle.modules.vehicle.service.IVehicleRepairRecordService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 车辆基本信息Service业务层处理
 *
 * @author ckk
 * @date 2025-06-24
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class VehicleBasicInfoServiceImpl extends ServiceImpl<VehicleBasicInfoMapper, VehicleBasicInfo> implements IVehicleBasicInfoService {

    private final VehicleBasicInfoMapper baseMapper;
    private final IVehicleInsuranceInfoService insuranceInfoService;
    private final IVehicleRepairRecordService repairRecordService;
    private final IVehicleAnnualInspectionRecordService annualInspectionRecordService;

    /**
     * 查询车辆基本信息
     *
     * @param id 主键
     * @return 车辆基本信息
     */
    @Override
    public VehicleBasicInfoVo queryById(Long id) {
        // 查询车辆基本信息
        VehicleBasicInfoVo vo = baseMapper.selectVoById(id);
        Assert.notNull(vo, () -> new ServiceException("车辆基本信息不存在"));

        // 查询保险信息
        vo.setInsuranceInfos(BeanUtil.copyToList(insuranceInfoService.lambdaQuery().eq(VehicleInsuranceInfo::getVehicleId, id).list(), VehicleInsuranceInfoVo.class));

        // 查询维修记录
        vo.setRepairRecords(BeanUtil.copyToList(repairRecordService.lambdaQuery().eq(VehicleRepairRecord::getVehicleId, id).list(), VehicleRepairRecordVo.class));

        // 查询年审信息
        vo.setAnnualInspectionRecords(BeanUtil.copyToList(annualInspectionRecordService.lambdaQuery().eq(VehicleAnnualInspectionRecord::getVehicleId, id).list(), VehicleAnnualInspectionRecordVo.class));

        return vo;
    }

    /**
     * 分页查询车辆基本信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 车辆基本信息分页列表
     */
    @Override
    public TableDataInfo<VehicleBasicInfoVo> queryPageList(VehicleBasicInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<VehicleBasicInfo> lqw = buildQueryWrapper(bo);
        Page<VehicleBasicInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        CollUtil.forEach(result.getRecords(), (vo, i) -> {
            // 获取保险信息
            insuranceInfoService.lambdaQuery()
                .select(VehicleInsuranceInfo::getInsuranceEndDate)
                .eq(VehicleInsuranceInfo::getVehicleId, vo.getId())
                .orderByDesc(VehicleInsuranceInfo::getInsuranceEndDate)
                .last("limit 1")
                .oneOpt()
                .map(VehicleInsuranceInfo::getInsuranceEndDate)
                .ifPresent(insuranceEndDate -> {
                    vo.setInsuranceEndDate(insuranceEndDate);
                    // 保险状态（0：正常，1：临期（一个月内），2：超期）
                    vo.setInsuranceStatus(
                        DateTime.now().isAfter(insuranceEndDate) ? 2 :
                            (insuranceEndDate.before(DateTime.now().offset(DateField.MONTH, 1)) ? 1 : 0)
                    );
                });

            // 获取年检信息
            annualInspectionRecordService.lambdaQuery()
                .select(VehicleAnnualInspectionRecord::getValidityEndDate)
                .eq(VehicleAnnualInspectionRecord::getVehicleId, vo.getId())
                .orderByDesc(VehicleAnnualInspectionRecord::getValidityEndDate)
                .last("limit 1")
                .oneOpt()
                .map(VehicleAnnualInspectionRecord::getValidityEndDate)
                .ifPresent(validityEndDate -> {
                    vo.setValidityEndDate(validityEndDate);
                    // 年检状态（0：正常，1：临期（一个月内），2：超期）
                    vo.setValidityStatus(
                        DateTime.now().isAfter(validityEndDate) ? 2 :
                            (validityEndDate.before(DateTime.now().offset(DateField.MONTH, 1)) ? 1 : 0)
                    );
                });

            // 购置日期状态（0：正常，1：临期（一个月内），2：超期）
            vo.setPurchaseDateStatus(
                DateTime.now().isAfter(vo.getPurchaseDate()) ? 2 :
                    (vo.getPurchaseDate().before(DateTime.now().offset(DateField.MONTH, 1)) ? 1 : 0)
            );

        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的车辆基本信息列表
     *
     * @param bo 查询条件
     * @return 车辆基本信息列表
     */
    @Override
    public List<VehicleBasicInfoVo> queryList(VehicleBasicInfoBo bo) {
        LambdaQueryWrapper<VehicleBasicInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<VehicleBasicInfo> buildQueryWrapper(VehicleBasicInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<VehicleBasicInfo> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getLicensePlate()), VehicleBasicInfo::getLicensePlate, bo.getLicensePlate());
        lqw.eq(bo.getModel() != null, VehicleBasicInfo::getModel, bo.getModel());
        lqw.eq(StringUtils.isNotBlank(bo.getUsageNature()), VehicleBasicInfo::getUsageNature, bo.getUsageNature());
        return lqw;
    }

    /**
     * 新增车辆基本信息
     *
     * @param bo 车辆基本信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(VehicleBasicInfoBo bo) {
        VehicleBasicInfo add = MapstructUtils.convert(bo, VehicleBasicInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改车辆基本信息
     *
     * @param bo 车辆基本信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(VehicleBasicInfoBo bo) {
        VehicleBasicInfo update = MapstructUtils.convert(bo, VehicleBasicInfo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(VehicleBasicInfo entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除车辆基本信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
